import axios from 'axios'
import store from '@/store/index'
import { Message } from 'element-ui'
import baseURL from "./baseUrl"
// import { reject, resolve } from 'core-js/fn/promise'
const http = {}

var instance = axios.create({
    timeout: 60000,
    baseURL
})

//添加请求拦截器

instance.interceptors.request.use(
    function (config) {
        //请求头添加token
        // if (store.state.UserToken) {
        //     config.headers.Authorization = store.state.UserToken
        // }
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)


//响应拦截器异常处理
instance.interceptors.response.use(
    response => {
        return response.data
    },
    err => {
        if (err && err.response) {
            switch (err.response.status) {
                case 400:
                    err.message = "请求出错"
                    break
                case 401:
                    Message.error({
                        message: '授权失败，请重新登录'
                    })

                    store.commit('LOGIN_OUT')
                    setTimeout(() => {
                        window.location.reload()
                    }, 1000)
                    break
                case 403:
                    err.message = "拒绝访问"
                    break
                case 404:
                    err.message = "请求错误,请求资源未找到"
                    break
                case 500:
                    err.message = "服务端出错"
                    break


            }
        } else {
            err.message = "服务端出错"
        }

        Message.error({
            message: err.message
        })
        return Promise.reject(err.message)
    }
)



http.get = function (url, data) {
    return new Promise((resolve, reject) => {
        instance.get(url, data).then(reponse => {
            if (reponse.code === 200) {
                
                resolve(reponse)
            } else {
                Message.error({
                    message: reponse.message
                })

                reject(reponse.message)
            }
        })
            .catch(e => {
                console.log(e);
            })
    })
}


http.post = function (url, data, options) {
    return new Promise((resolve, reject) => {
        instance.post(url, data, options).then(reponse => {
            if (reponse.code === 200) {
                resolve(reponse.data)
            } else {
                Message.error({
                    message: reponse.message
                })

                reject(reponse.message)
            }
        })
            .catch(e => {
                console.log(e);
            })
    })
}




export default http